from py2neo import Graph, Node
import json

# Neo4j 连接信息
NEO4J_URI = "bolt://localhost:7687"
NEO4J_USER = "neo4j"
NEO4J_PASSWORD = "123456"

# 保存的文件名（直接在当前目录）
OUTPUT_FILENAME = "final_inspections.jsonl"

def node_to_dict_with_Id(node: Node):
    return {
        "identity": node.identity,
        "labels": list(node.labels),
        "properties": dict(node)
    }

def query_drawing_final_inspection(drawing_id):
    # 连接数据库
    graph = Graph(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
    
    # 执行查询
    cypher_query = """
    MATCH (d:图纸 {图纸ID: $drawing_id})-[:有终检项]->(fi:终检)
    RETURN fi AS 终检
    """
    result = graph.run(cypher_query, drawing_id=drawing_id)
    
    # 处理结果并转换格式
    return [node_to_dict_with_Id(record["终检"]) for record in result]

def save_to_jsonl(data, filename):
    # 直接在当前目录写入jsonl文件
    with open(filename, "w", encoding="utf-8") as f:
        for item in data:
            json.dump(item, f, ensure_ascii=False)
            f.write("\n")  # 每行一个JSON对象
    
    print(f"结果已保存到当前目录: {filename}")

# 运行示例
if __name__ == "__main__":
    drawing_id = "2c9212b3958edc700195cafc96316b85"
    results = query_drawing_final_inspection(drawing_id)
    save_to_jsonl(results, OUTPUT_FILENAME)
    